/*
 * Powered By [信安]
 * Since 2013 - 2013
 */


package com.xinan.system.curd;

import com.jfinal.aop.Before;
import com.jfinal.core.BaseController;
import com.jfinal.core.Const;
import com.jfinal.ext.interceptor.SearchSql;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.render.JsonRender;
import com.xinan.utils.Constants;
import com.xinan.utils.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author EricLee
 * @version 1.0
 * @since 1.0
 */

public class AuthUserController extends CurdController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    public void user() {
            render("/WEB-INF/views/system/authindex.html");
    }
    public void getuser() {
        String mc= getPara("mc");
        String dm=getPara("dm");
        if ( StringKit.notBlank(mc)){
            setAttr("mc",mc);
        }
        if( StringKit.notBlank(dm)){
            setAttr("dm",dm);
        }
        render("/WEB-INF/views/js/ddxx/lxr.html");
    }

    public void getuserindex() {
        String tbName = "auth_user";
        String fields = "";
        String orgid=getPara("orgid");
        String pid=getPara("pid");
        setAttr("orgid",orgid)    ;
        setAttr("pid",pid);
        String mc= getPara("mc");
        String dm=getPara("dm");
        if ( StringKit.notBlank(mc)){
            setAttr("mc",mc);
        }
        if( StringKit.notBlank(dm)){
            setAttr("dm",dm);
        }
        if (buildView(tbName, fields)) {
            render("/WEB-INF/views/js/ddxx/authUser.html");
        }
    }

    @Override
    public void index() {
        String tbName = "auth_user";
        String fields = "";
        String orgid=getPara("orgid");
        String pid=getPara("pid");
        setAttr("orgid",orgid)    ;
        setAttr("pid",pid);
        if (buildView(tbName, fields)) {
            render("/WEB-INF/views/system/authUser.html");
        }
    }

    /**
     * 在增加了SearchSql拦截之后，就可以根据页面的配置信息
     * 自动装配查询语句，并放入request中，可以通过getAttr(Const.SEARCH_SQL)函数获取到
     * 根据实际需要自动组装到sql语句中
     */
    @Override
    @Before(SearchSql.class)
    public void query() {
        int pageNumber = getParaToInt("page");
        int pageSize = getParaToInt("rows");
        String sqlExp = "from auth_user";
        String where = getAttr(Const.SEARCH_SQL);
        String userName = getAttr(Constants.USER_NAME);
//        if (StringKit.notBlank(where)) {
//            where += " and optname = '" + userName + "'";
//        } else {
//            where += " optname = '" + userName + "'";
//        }
        // 查询条件为空 按照组织机构查询 不为空按照查询条件查询
        if (!StringKit.notBlank(where)) {
            String orgid = getPara("orgid");
            if (StringKit.notBlank(orgid)) {
                where += "  orgid = '" + orgid + "'";
            }
        }

        if (StringKit.notBlank(where)) {
            sqlExp += " where " + where;
        }

        Page<Record> page = Db.paginate(pageNumber, pageSize, "select *", sqlExp);
        Map root = new HashMap();
     	root.put("total", page.getTotalRow());
     	root.put("rows", page.getList());
     	renderJson(JsonKit.toJson(root));
    }

    /**
     * 更新用户密码
     * 20130802-add
     */
    public void updataPassword(){
        boolean flag = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
           String pwd=getPara("password");
           int id=getParaToInt("id");
           boolean uFlag=AuthUser.dao.findById(id).set("password", pwd).update();
           return uFlag;
            }
        });
        if(flag){
        //    renderJson(Constants.DELETESUCCESS);
			render(new JsonRender(Constants.DELETESUCCESS).forIE());

        }else{
          //  renderJson(Constants.DELETEFAILED);
			render(new JsonRender(Constants.DELETEFAILED).forIE());

        }
    }
    /**
     * 保存数据
     */
    @Override
    public void save() {
        //清除缓存
        CacheKit.removeAll("orguserTree");
        // 校验用户唯一性
        String name=getPara("username") ;


        List<Record> usernames = Db.find("select  * from  auth_user  where    username=  '"+name+"'");
        if(usernames.size() >0){
            renderJson("存在此用户");
        } else{
        boolean flag = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
            boolean sFlag;
            try {
                String userName = getAttr(Constants.USER_NAME);
                String pass=getPara("password");
                String key =Constants.KEY;
                String newpass="";
                newpass = DigestUtils.encrypt(pass, key);
                AuthUser user = getModel(AuthUser.class);
                user.set("optname", userName).set("password",newpass);
                /*String zpPath = getPara("zp_file");
                if (StringKit.notBlank(zpPath)) {
                    File f = new File(PathKit.getWebRootPath() + zpPath);
                    if (f.exists()) {
                        FileInputStream fin = new FileInputStream(f);
                        user.set("zp", Base64.encode(IOUtils.toByteArray(fin), Base64.DEFAULT));
                        fin.close();
                        f.delete();//操作成功之后，直接删除临时文件
                    }
                }*/
                sFlag = user.save();
                String roles = getPara("roleIds");
                if (sFlag && StringKit.notBlank(roles)) {
                    String[] roleIds = roles.split(",");
                    String sql = "insert into auth_user_role(userid,roleid,optname) values (?,?,?)";
                    int count = roleIds.length;
                    Object[][] params = new Object[count][3];
                    for (int i = 0; i < count; i++) {
                        params[i][0] = user.getId();
                        params[i][1] = roleIds[i];
                        params[i][2] = userName;
                    }
                    Db.batch(sql, params, count);
                }
                String perms = getPara("permIds");
                if (sFlag && StringKit.notBlank(perms)) {
                    String[] permIds = perms.split(",");
                    String sql = "insert into auth_user_permission(userid,permissionid,optname) values (?,?,?)";
                    int count = permIds.length;
                    Object[][] params = new Object[count][3];
                    for (int i = 0; i < count; i++) {
                        params[i][0] = user.getId();
                        params[i][1] = permIds[i];
                        params[i][2] = userName;
                    }
                    Db.batch(sql, params, count);
                }
            } catch (Exception e) {
                sFlag = false;
                logger.error("保存照片到数据库出现异常：" + e.getMessage());
            }
            return sFlag;
            }
        });
        if (flag) {
        //    renderJson(Constants.SAVESUCCESS);
			render(new JsonRender(Constants.SAVESUCCESS).forIE());

        } else {
         //   renderJson(Constants.SAVEFAILED);
			render(new JsonRender(Constants.SAVEFAILED).forIE());

        }
        }
    }

    /**
     * Post请求的菜单更新函数，可以接受菜单的id和菜单对象，并根据菜单id进行更新，并返回影响行数，据此判断是否操作成功
     * 此处使用rose框架的rest风格url，可以把参数作为路径的一部分进行传递
     */
    @Override
    public void update() {
        //清除缓存
        CacheKit.removeAll("orguserTree");
        boolean flag = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
            boolean sFlag;
            try {
                String userName = getAttr(Constants.USER_NAME);
                AuthUser user = getModel(AuthUser.class);
                user.set("optname", userName);
                /*String zpPath = getPara("zp_file");
                if (StringKit.notBlank(zpPath)) {
                    File f = new File(PathKit.getWebRootPath() + zpPath);
                    if (f.exists()) {
                        FileInputStream fin = new FileInputStream(f);
                        user.set("zp", Base64.encode(IOUtils.toByteArray(fin), Base64.DEFAULT));
                        fin.close();
                        f.delete();//操作成功之后，直接删除临时文件
                    }
                }*/
                sFlag = user.update();
                String strDelSql = "delete from auth_user_role where userid=?";
                Db.update(strDelSql, user.getId());
                String roles = getPara("roleIds");
                if (sFlag && StringKit.notBlank(roles)) {
                    String[] roleIds = roles.split(",");
                    String sql = "insert into auth_user_role(userid,roleid,optname) values (?,?,?)";
                    int count = roleIds.length;
                    Object[][] params = new Object[count][3];
                    for (int i = 0; i < count; i++) {
                        params[i][0] = user.getId();
                        params[i][1] = roleIds[i];
                        params[i][2] = userName;
                    }
                    Db.batch(sql, params, count);
                }
                String perms = getPara("permIds");
                if (sFlag && StringKit.notBlank(perms)) {
                    String[] permIds = perms.split(",");
                    String strDelSqls = "delete from auth_user_permission where userid=?";
                    Db.update(strDelSqls, user.getId());
                    String sql = "insert into auth_user_permission(userid,permissionid,optname) values (?,?,?)";
                    int count = permIds.length;
                    Object[][] params = new Object[count][3];
                    for (int i = 0; i < count; i++) {
                        params[i][0] = user.getId();
                        params[i][1] = permIds[i];
                        params[i][2] = userName;
                    }
                    Db.batch(sql, params, count);
                }
            } catch (Exception e) {
                sFlag = false;
                logger.error("保存照片到数据库出现异常：" + e.getMessage());
            }
            return sFlag;
            }
        });
        if (flag) {
       //     renderJson(Constants.EDITSUCCESS);
			render(new JsonRender(Constants.EDITSUCCESS).forIE());

        } else {
         //   renderJson(Constants.EDITFAILED);
			render(new JsonRender(Constants.EDITFAILED).forIE());

        }
    }

    /**
     * 在删除用户的时候，顺带删除其赋予的角色
     */
    @Override
    public void delete() {
        //清除缓存
        CacheKit.removeAll("orguserTree");
        boolean flag = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {

                boolean dFlag = AuthUser.dao.deleteById(getParaToInt());
                boolean uFlag = Db.deleteById("auth_user_role","userid",getParaToInt());
                boolean pFlag = Db.deleteById("auth_user_permission","userid",getParaToInt());

                return dFlag || uFlag || pFlag;
            }
        });
        if (flag) {
         //   renderJson(Constants.DELETESUCCESS);
			render(new JsonRender(Constants.DELETESUCCESS).forIE());

        } else {
         //   renderJson(Constants.DELETEFAILED);
			render(new JsonRender(Constants.DELETEFAILED).forIE());

        }
    }
    /**
     * 人员照片上传，存在临时目录中，并生成对应的访问路径，以便在页面上预览
     */
    /*public void upload() {
        UploadFile zp = getFile();
        Map<String, String> map = new HashMap<String, String>();
        if (zp != null) {
            map.put("img", "/upload/" + zp.getFileName());
        } else {
            map.put("msg", "文件上传失败！");
        }
        renderJson(map);
    }*/

    /**
     * 根据用户编号，从数据库中获取照片二进制文件，并进行base64解码，然后展示到页面上
     */
    /*public void download() {
        try {
            int id = getParaToInt(0);
            AuthUser u = AuthUser.dao.findById(id);
            if (u.getZp() != null) {
                OutputStream os = getResponse().getOutputStream();
                IOUtils.write(Base64.decode(u.getZp(), Base64.DEFAULT), os);
                os.flush();
                os.close();
            }
        } catch (IOException e) {
            logger.error("从数据库读取照片出现异常：" + e.getMessage());
        }
        renderNull();
    }*/

    /**
     * 根据用户编号生成角色树
     */
    public void rolesTree() {
        AuthUser u = getSessionAttr(Constants.LOGIN_USER);
        if (u != null) {
            String userId = getPara(0);
            List<String> roleList = null;
            if (StringKit.notBlank(userId)) {
                String permSql = "select roleid from auth_user_role where userid=?";
                roleList = Db.query(permSql, userId);
            }

            List<Record> list;
            if (u.getUsername().equals("admin")) {
                String strSql = "select id, name as text from auth_role";
                list = Db.find(strSql);
            } else {
                String roleSql = "select a.id, a.name as text from auth_role a,auth_user_role b where b.userid = ? and a.id = b.roleid";
                list = Db.find(roleSql, u.getId());
            }
            if (roleList != null) {
                for (Record r : list) {
                    if (roleList.contains(r.get("id"))) {
                        r.set("checked", true);
                    } else {
                        r.set("checked", false);
                    }
                }
            }
            renderJson(list);
        }
    }
}

